using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TVT.UI.Helpers;
using System.Collections.Generic;
using TVT.Common.Exceptions;
using TVT.UI.EventArguments;
using TVT.Common.Helpers;
using TVT.BizLayer.Entities;
using System.IO;


namespace TVT.UI.UserControls
{
    public partial class ListMatchs : System.Web.UI.UserControl
    {
        #region Events

        public event EventHandler OnContactUser = null;

        public void ContactUser(UserEventArgs args)
        {
            if (OnContactUser != null)
            {
                OnContactUser(this, args);
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["SortExpression"] = "LastName DESC";
                gvMatchs.PageSize = Int32.Parse(ConfigurationManager.AppSettings[WellKnownKeys.GridViewsPageSizeKey]);
                try
                {
                    BindData();                    
                }
                catch (FunctionalException ex)
                {
                    lblTransactionResultMessage.Text = ex.Message;
                }
            }
        }

        private void BindData()
        {
             User logUser = User.Find((Guid)Membership.GetUser().ProviderUserKey);
             if (logUser.UserProfile.EigenFaceDistance == 0)
                 return;
             List<string> rolesOk = new List<string>();
             foreach (string r in Roles.GetAllRoles())
             {
                 if (r != WellKnownKeys.AdministratorRolKey)
                     rolesOk.Add(r);
             }

             IEnumerable<User> usersEnum = logUser.FindMatchs();
             List<User> users = new List<User>();
             bool results = false;
             foreach (User item in usersEnum)
	         {
                 results = true;
                 users.Add(item);
             }
		     if(!results)
             {
                 lblTransactionResultMessage.Text = Resources.NoResultsFound;
                 lblTransactionResultMessage.Visible = true;
             }
             else
             {
                 lblTransactionResultMessage.Visible = false;
                 pnlSearchMatchsResults.Visible = true;
             }

            gvMatchs.DataSource = users;
            ViewState["SortableListMatchs"] = users;
            gvMatchs.DataBind();
        }

        protected void gvMatchs_PageIndexChanging(Object sender, GridViewPageEventArgs e)
        {            
            gvMatchs.PageIndex = e.NewPageIndex;
            if (gvMatchs.EditIndex != -1)
            {      
                e.Cancel = true;             
                int newPageNumber = e.NewPageIndex + 1;                
            }
            else
            {
                DataView dataView = new DataView(GetDataTableFromMatchsList((List<User>)ViewState["SortableListMatchs"]));

                dataView.Sort = ViewState["SortExpression"].ToString();
                gvMatchs.DataSource = dataView;
                gvMatchs.DataBind();
            }

        }

        protected void OnSortingGvMatchs(object sender, GridViewSortEventArgs e)
        {
            string sort = " DESC";

            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            else
            {
                if ((SortDirection)ViewState["sortDirection"] == SortDirection.Ascending)
                {
                    ViewState["sortDirection"] = SortDirection.Descending;
                    sort = " DESC";
                }
                else
                {
                    ViewState["sortDirection"] = SortDirection.Ascending;
                    sort = " ASC";
                }
            }

            List<User> users = (List<User>)ViewState["SortableListMatchs"];
            DataTable dataTable = GetDataTableFromMatchsList(users);

            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);

                dataView.Sort = e.SortExpression + sort;
                ViewState["SortExpression"] = e.SortExpression + sort;
                gvMatchs.DataSource = dataView;
                gvMatchs.DataBind();
            }
        }        

        private DataTable GetDataTableFromMatchsList(List<User> users)
        {
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("UserId");
            dataTable.Columns["UserId"].DataType = System.Type.GetType("System.Guid");
            
            dataTable.Columns.Add("UserName");
            dataTable.Columns["UserName"].DataType = System.Type.GetType("System.String");

            dataTable.Columns.Add("Age");
            dataTable.Columns["Age"].DataType = System.Type.GetType("System.String");

            dataTable.Columns.Add("MatchLevel");
            dataTable.Columns["MatchLevel"].DataType = System.Type.GetType("System.String");

            DataRow dataRow;

            foreach (User user in users)
            {
                dataRow = dataTable.NewRow();

                dataRow["UserId"] = user.UserId;
                dataRow["UserName"] = user.UserName;
                dataRow["Age"] = user.Age.ToString();
                dataRow["MatchLevel"] = ((int)user.Match).ToString() + " % ";

                dataTable.Rows.Add(dataRow);
            }

            return dataTable;
        }

        protected void gvMatchs_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            StylesApplier stylesApplier = new StylesApplier();
            Guid idUser = Guid.Empty;
            try
            {
                stylesApplier.GridViewStyle(e.Row);

                User user = null;
                user = ((User)(e.Row.DataItem));

                if ((user != null) && (user.UserId != Guid.Empty))
                {
                    idUser = user.UserId;
                    user = ((User)(e.Row.DataItem));

                    Image imgUser = (Image)e.Row.FindControl("imgUser");
                    String imgUrl = ConfigurationManager.AppSettings[WellKnownKeys.TemporaryFilesPathKey].ToString() + user.UserName + ".jpg";
                    String fullPath = imgUrl.Replace("~", AppDomain.CurrentDomain.BaseDirectory);
                    if (File.Exists(fullPath))
                        imgUser.ImageUrl = imgUrl;

                    Label lblUserName = (Label)e.Row.FindControl("lblUserName");
                    lblUserName.Text = user.UserName;

                    Label lblMatchLevel = (Label)e.Row.FindControl("lblMatchLevel");
                    lblMatchLevel.Text = ((int)user.Match).ToString() + " % ";

                    Label lblAge = (Label)e.Row.FindControl("lblAge");
                    lblAge.Text = user.Age.ToString();
                   
                }
            }

            catch (Exception)
            {
                idUser = new Guid(((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString());
                                
                Label lblAge = (Label)e.Row.FindControl("lblAge");
                lblAge.Text = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[2].ToString();

                Label lblMatchLevel = (Label)e.Row.FindControl("lblMatchLevel");
                lblMatchLevel.Text = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[3].ToString();

                Label lblUserName = (Label)e.Row.FindControl("lblUserName");
                lblUserName.Text = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[4].ToString();
               
            }

            if (idUser != Guid.Empty)
            {

                ImageButton lbtnDiscard = (ImageButton)e.Row.FindControl("lbtnDiscard");
                lbtnDiscard.CommandArgument = idUser.ToString();

                ImageButton lbtnContact = (ImageButton)e.Row.FindControl("lbtnContact");
                lbtnContact.CommandArgument = idUser.ToString();
            }
        }

        protected void gvMatchs_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            if (e.CommandName == "DiscardUser")
            {
                lblTransactionResultMessage.Visible = true;
                
                try
                {
                    Guid userId = new Guid(id);
                    Guid usserIdLogged = (Guid)Membership.GetUser().ProviderUserKey;
                    UserRelation userRelation = new UserRelation() { UserId1 = usserIdLogged, UserId2 = userId, Status = Enumerators.RelationStatus.Discarded };
                    userRelation.Save();

                    BindData();
                   
                }
                catch (FunctionalException ex)
                {
                    lblTransactionResultMessage.Text = ex.Message;
                }
            }

            if (e.CommandName == "ContactUser")
            {
                try
                {
                    UserEventArgs args = new UserEventArgs();
                    args.IdUser = new Guid(e.CommandArgument.ToString());
                    ContactUser(args);
                }
                catch (FunctionalException ex)
                {
                    lblTransactionResultMessage.Text = ex.Message;
                }
            }
        }
    }
}